#! /usr/bin/python3 python3
# -*- coding: utf-8 -*-

# *************************************************************
#  Projectname @  pysm
#     Filename @  upload.py
#       Author @  Steve.ma
#  Create date @  2018/9/7
#  Description @  
# *************************************************************

from .. import api_blueprint
from Models.ApiController import *
from Cache import CachePath
import  os

from Library.Oss import  *

class UploadController(ApiControllerModel) :
    Controller = 'Upload'
    def index(self, params=None):
        import time
        ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])
        files = self.getFiles()

        oss = SMOss()

        res = {}

        for key in files.keys():
            f = request.files[key]  # 从表单获取文件
            if f and self.allowed_file(f.filename, ALLOWED_EXTENSIONS):  # 判断是否是允许上传的文件类型
                # 获取文件后缀
                ext = f.filename.rsplit('.', 1)[1]
                # OSS 上封装的获取新的文件名
                new_filename = oss.newFileName(ext)
                # 保存文件到Cache目录
                f.save(os.path.join(CachePath, new_filename))
                # 上传到OSS
                upload = oss.upload(oss.newObjectName(new_filename), CachePath+'/'+new_filename);
                # 无论成功与否 本地的文件是要删除的
                if os.path.exists(CachePath+'/'+new_filename):
                    os.remove(CachePath+'/'+new_filename)
                # 上传成功或者失败
                if upload['httpstatus'] == '200' :
                    res[key] = upload['url']
        if res :
            return self.returnMsg(True, res)
        else :
            return self.returnMsg(False, {
                "code" : 10010,
                "message" : "上传失败"
            })



Controller = UploadController();

@api_blueprint.route('/upload', methods=['GET', 'POST'])
def UploadIndex():
    return Controller.index()
